package com.baor.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baor.dao.CustomerDao;
import com.baor.domain.CustomerVO;
import com.baor.service.CustomerService;
import com.baor.util.R;
import com.github.yulichang.query.MPJQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerDao customerDao;

    @Override
    public R deductPoints(Map<String, Object> params) {
        try {
            // 1. 参数校验
            if (params.get("Id") == null || params.get("deductPoints") == null) {
                return R.er("用户ID和扣除积分不能为空");
            }
            Long Id = Long.parseLong(params.get("Id").toString());
            Integer deductPoints = Integer.parseInt(params.get("deductPoints").toString());
            if (deductPoints <= 0) {
                return R.er("扣除积分必须大于0");
            }
            String reason = params.get("reason") != null ? params.get("reason").toString() : "无原因";

            // 2. 查询用户是否存在
            CustomerVO customerVO = customerDao.selectById(Id);
            if (customerVO == null) {
                return R.er("用户不存在");
            }

            // 3. 校验积分是否充足（假设用户积分字段为 integral）
            Integer currentPoints = customerVO.getPointsTotal()!= null ? customerVO.getPointsTotal() : 0;
            if (currentPoints < deductPoints) {
                return R.er("用户积分不足，当前积分：" + currentPoints);
            }

            // 4. 计算新积分并更新
            customerVO.setPointsTotal(currentPoints - deductPoints);
            int updateCount = customerDao.updateById(customerVO);
            if (updateCount > 0) {
                return R.ok("积分扣除成功，扣除：" + deductPoints + "，剩余：" + customerVO.getPointsTotal() + "，原因：" + reason);
            } else {
                return R.er("积分扣除失败");
            }
        } catch (NumberFormatException e) {
            return R.er("参数格式错误，请检查用户ID和扣除积分是否为数字");
        } catch (Exception e) {
            e.printStackTrace();
            return R.er("系统异常：" + e.getMessage());
        }
    }



    //以下家豪
    @Override
    public R customerList(Map<String, Object> params) {
        try {
            Page page = new Page();
            page.setCurrent((int)params.get("pageIndex"));
            page.setSize((int)params.get("pageSize"));
            MPJQueryWrapper<CustomerVO> wrapper = new MPJQueryWrapper<>();
            wrapper .select("t.id", "t.realname", "t.nickname", "t.phone",
                    "t.delivery_total", "t.points_total", "t.last_active_time",
                    "t.register_time", "t.status", "t.inviter_id",
                    "t.organization");

            if (params.get("keyword") != null && !params.get("keyword").toString().trim().isEmpty()) {
                String keyword = params.get("keyword").toString().trim();
                wrapper.nested(wq -> wq
                        .like("t.realname", keyword)
                        .or()
                        .like("t.phone", keyword)
                );

            }
//           按活跃时间

            if (params.get("startTime") != null && params.get("endTime") != null) {
                String startTime = params.get("startTime").toString();
                String endTime = params.get("endTime").toString();
                wrapper.between("last_active_time", startTime, endTime);
            }


            // 组织机构查询
            if (params.get("organization") != null && !params.get("organization").toString().trim().isEmpty()) {
                wrapper.like("organization", params.get("organization").toString().trim());
            }

            // 状态查询 - 简化处理（只有正常和异常）
            if (params.get("status") != null && !params.get("status").toString().trim().isEmpty()) {
                String status = params.get("status").toString().trim();

                // 方式1：支持中文状态名查询
                if ("正常".equals(status)) {
                    wrapper.eq("status", 1); // 假设1表示正常
                } else if ("禁用".equals(status)) {
                    wrapper.eq("status", 0); // 假设0表示异常
                }
            }
            wrapper.orderByDesc("last_active_time");

            IPage<CustomerVO> iPage = this.customerDao.selectPage(page, wrapper);
            Map<String, Object> map = new HashMap<>();
            map.put("totalSize", iPage.getTotal());
            map.put("customerList", iPage.getRecords());

            return R.ok(map);



        } catch (Exception e) {
            System.out.println(e);
            return R.er("查询失败：");
        }
    }

    @Override
    public Boolean editUser(Map<String, Object> params) {
        LambdaUpdateWrapper<CustomerVO> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(CustomerVO::getOrganization, params.get("organization"))
                .set(CustomerVO::getNickname, params.get("nickname"))
                .set(CustomerVO::getPhone, params.get("phone"))
                .eq(CustomerVO::getId, params.get("id"));
        if (params.get("status") != null && !params.get("status").toString().trim().isEmpty()) {
            String status = params.get("status").toString().trim();
            if ("正常".equals(status)) {
                wrapper.set(CustomerVO::getStatus, 1); // 假设1表示正常
            } else if ("禁用".equals(status)) {
                wrapper.set(CustomerVO::getStatus, 2); // 假设0表示异常
            }
        }
        if (params.get("remark") != null && !params.get("remark").toString().trim().isEmpty()) {
            String remark = params.get("remark").toString().trim();
            wrapper.set(CustomerVO::getRemark, remark);
        }
        if (params.get("is_installer") != null && !params.get("is_installer").toString().trim().isEmpty()) {
            String is_installer = params.get("is_installer").toString().trim();
            if ("否".equals(is_installer)) {
                wrapper.set(CustomerVO::getIsInstaller, 0);
            } else if ("是".equals(is_installer)) {
                wrapper.set(CustomerVO::getIsInstaller, 1);
            }
        }
        if (params.get("is_collector") != null && !params.get("is_collector").toString().trim().isEmpty()) {
            String is_collector = params.get("is_collector").toString().trim();
            if ("否".equals(is_collector)) {
                wrapper.set(CustomerVO::getIsCollector, 0);
            } else if ("是".equals(is_collector)) {
                wrapper.set(CustomerVO::getIsCollector, 1);

            }
        }
        int update = customerDao.update(wrapper);
        if(update>0) {
            return true ;
        }else {
            return false ;
        }


    }

    @Override
    public R agentList(Map<String, Object> params) {
        String keyword = params.get("keyword").toString().trim();
//        if(keyword!=null && !keyword.trim().isEmpty()) {
//
//        }
        return null;
    }
}